/**
 * @file blasteroids.c
 * @brief engine of the game. All logic and settings are here
 */

/* Allegro */
#include <allegro5/allegro.h>
/* Standard */
#include <stdio.h>
#include <stdbool.h>
/* Project */
#include <blasteroids.h>
#include <movement.h>

void blasteroids_check_controls() {
  extern ALLEGRO_EVENT *event;
  extern bool *keys;
  if (event->type == ALLEGRO_EVENT_KEY_DOWN) {
    switch (event->keyboard.keycode) {
      case ALLEGRO_KEY_UP: {
        keys[FW] = true;
        break;
      }
      case ALLEGRO_KEY_DOWN: {
        keys[BW] = true;
        break;
      }
      case ALLEGRO_KEY_LEFT: {
        keys[CC] = true;
        break;
      }
      case ALLEGRO_KEY_RIGHT: {
        keys[CW] = true;
        break;
      }
      case ALLEGRO_KEY_ESCAPE: {
        keys[EX] = false;
        break;
      }
      default: {
      }
    }
  }
  if (event->type == ALLEGRO_EVENT_KEY_UP) {
    switch (event->keyboard.keycode) {
      case ALLEGRO_KEY_UP: {
        keys[FW] = false;
        break;
      }
      case ALLEGRO_KEY_DOWN: {
        keys[BW] = false;
        break;
      }
      case ALLEGRO_KEY_LEFT: {
        keys[CC] = false;
        break;
      }
      case ALLEGRO_KEY_RIGHT: {
        keys[CW] = false;
        break;
      }
      default: {
        break;
      }
    }
  }
  if (event->type == ALLEGRO_EVENT_DISPLAY_CLOSE) {
    keys[EX] = false;
  }
}

void blasteroids_input(Spaceship *s) {
  extern bool *keys;
  if (keys[FW]) {
    ship_speed(s, accel);
  }
  if (keys[BW]) {
    ship_speed(s, brake);
  }
  if (keys[CW]) {
    ship_rotate(s, right);
  }
  if (keys[CC]) {
    ship_rotate(s, left);
  }
}

void blasteroids_update(Spaceship *s, Asteroid **a) {
  al_clear_to_color(BG_COLOR);
  blasteroids_input(s);
  ship_update(s);
  asteroids_update(a);
  al_flip_display();
}

void blasteroids_loop(void) {
  extern bool *keys;
  extern ALLEGRO_EVENT *event;
  extern ALLEGRO_EVENT_QUEUE *queue;
  extern ALLEGRO_TIMER *timer;
  Spaceship *s = calloc(SHIP_MAX, sizeof(Spaceship));
  Asteroid **a = calloc(ASTEROIDS_MAX, sizeof(Asteroid*));
  keys = calloc(KEYS_MAX, sizeof(bool));
  keys[EX] = true;
  ship_init(s);
  asteroids_init(a);
  for (al_wait_for_event(queue, event); keys[EX];
      al_wait_for_event(queue, event)) {
    blasteroids_check_controls();
    if (event->type == ALLEGRO_EVENT_TIMER) {
      blasteroids_update(s, a);
    }
  }
  blasteroids_exit(s, a, keys, event, timer, queue);
}

void blasteroids_exit(Spaceship *s, Asteroid **a, bool *keys,
    ALLEGRO_EVENT *event, ALLEGRO_TIMER *timer, ALLEGRO_EVENT_QUEUE *queue) {
  free(keys);
  free(s);
  free(event);
  asteroids_free(a);
  al_destroy_display(al_get_current_display());
  al_destroy_timer(timer);
  al_destroy_event_queue(queue);
}
